package org.zjt.rabbit.demo.ack;

import org.zjt.rabbit.demo.common.ContantsConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者接受后setMandatory，通知发布者自己已经确认。消费者得到确认通知
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //端口默认使用5672
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(ContantsConfig.USER);
        connectionFactory.setPassword(ContantsConfig.PASSWORD);


        /**
         * 开启确认模式(发布者必须把publisherConfirms设置为true)
         * 或者 template.setMandatory(true);
         */
        connectionFactory.setPublisherConfirms(true);



        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true);
        //设置交换器和路由键(hello-exchange已经在section1创建过)
        template.setExchange("hello-exchange");
        template.setRoutingKey("hola");


        /**
         * 消费者接收并确认（setMandatory）后，回调。 成功后回调
         */
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println(ack);
            }
        });

        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                System.out.println(message +"     " +i+"      "+s +"      "+s1 +"      "+s2);
            }
        });


        Message message = MessageBuilder.withBody("hello world".getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .build();
        for (int i = 0; i < 5; i++)
            template.send(message);



        channel.close();
        connection.close();
    }
}
